import { isArray } from 'lodash-es';
import { DirectiveBinding } from 'vue';

import { useUserStore } from '@/store';

function checkPermission(el: HTMLElement, binding: DirectiveBinding) {
  const userStore = useUserStore();
  const username = userStore.username;
  const { value } = binding;

  if (value) {
    let hasPermission = false;
    if (isArray(value)) {
      hasPermission = value?.some((item) => item === username);
    } else {
      hasPermission = value === username;
    }
    if (!hasPermission && el.parentNode) {
      el.parentNode.removeChild(el);
    }
  } else {
    throw new Error(`need users! Like v-user="['manager', 'administrator']"`);
  }
}

export default {
  created(el: HTMLElement, binding: DirectiveBinding) {
    checkPermission(el, binding);
  },
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    checkPermission(el, binding);
  },
  updated(el: HTMLElement, binding: DirectiveBinding) {
    checkPermission(el, binding);
  },
};
